//
//  FileManager+Additions.swift
//  MGExtensionsKit
//
//  Created by Max on 2020/6/24.
//

import Foundation

extension Extensive where Base == FileManager {
    
    
    /// 获取文件夹大小
    /// - Parameter path: 文件夹路径
    /// - Returns:  total bytes size
    public func directorySizeAtPath(_ path: String) -> Int64 {
        guard base.fileExists(atPath: path) else {
            return 0
        }
        var result: Int64 = 0
        base.subpaths(atPath: path)?.forEach({
            let subpath = (path as NSString).appendingPathComponent($0)
            if let attributes = try? base.attributesOfItem(atPath: subpath), let size = attributes[.size] as? Int64 {
                result += size
            }
        })
        return result
    }
    
    /// 删除文件夹下所有文件
    /// - Parameter path: 文件夹路径
    /// - Returns: 是否成功
    @discardableResult
    public func removeAllItemsOfDirectoryAtPath(_ path: String) -> Bool {
        guard base.fileExists(atPath: path),
            let subpaths = base.subpaths(atPath: path),
            !subpaths.isEmpty else {
            return false
        }
        for fileName in subpaths {
           let subpath = (path as NSString).appendingPathComponent(fileName)
            do {
                try base.removeItem(atPath: subpath)
            } catch {
                return false
            }
        }
        return true
    }

    
    /// 将image data写入沙盒
    /// - Parameter image: image
    /// - Returns: 成功返回沙盒文件路径，失败返回nil
    public func writeImageDataToTemporaryDirectory(image: UIImage) -> String? {
        let fileName = NSUUID().uuidString + ".jpeg"
        let finalPath = (NSTemporaryDirectory() as NSString).appendingPathComponent(fileName)
        guard let data = image.jpegData(compressionQuality: 1) else {
            return nil
        }
        do {
            try data.write(to: URL(fileURLWithPath: finalPath))
            return finalPath
        } catch {
            return nil
        }
    }
    
}
